{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 显存优化方式\n",
    "1. 批次调整\n",
    "2. 梯度累积\n",
    "3. 梯度检查点\n",
    "4. 优化器\n",
    "5. 冻结参数\n",
    "6. 减小token长度\n"
   ],
   "id": "9fefe5cb71ff941b"
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "import evaluate\n",
    "from transformers import DataCollatorWithPadding, Trainer, TrainingArguments\n",
    "\n",
    "from MyHelper import *"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "2776fc4177c3301b",
   "metadata": {},
   "source": "model, tokenizer = init_model_and_tokenizer(Config.hfl_chinese_macbert_large)",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "84d2e9c99c621550",
   "metadata": {},
   "source": "trainset, testset = init_dataset(tokenizer)",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "multi_metrics = evaluate.combine([\"accuracy\", \"f1\", \"recall\", \"precision\"])\n",
    "\n",
    "def eval_function(rt):\n",
    "    preds, labels = rt\n",
    "    preds = preds.argmax(axis=-1)\n",
    "    return multi_metrics.compute(preds, labels)"
   ],
   "id": "84b19c66836f52b5",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "76b3411f01a0832d",
   "metadata": {},
   "source": [
    "%%time\n",
    "start_gpu_memory, max_memory = init_memory()\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"./output\",\n",
    "    per_device_train_batch_size=32,\n",
    "    per_device_eval_batch_size=32,\n",
    "    max_steps=10,\n",
    "    # num_train_epochs=1,\n",
    "    eval_strategy=\"steps\",\n",
    "    logging_steps=10,\n",
    "    save_total_limit=2,\n",
    "    learning_rate=5e-5,\n",
    "    weight_decay=0.01,\n",
    "    metric_for_best_model=\"f1\",\n",
    "    load_best_model_at_end=True,\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=trainset,\n",
    "    eval_dataset=testset,\n",
    "    compute_metrics=eval_function,\n",
    "    tokenizer=tokenizer,\n",
    "    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),\n",
    ")\n",
    "\n",
    "trainer_state = trainer.train()\n",
    "memory_info(start_gpu_memory, max_memory, trainer_state)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "%%time\n",
    "start_gpu_memory, max_memory = init_memory()\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"./output\",\n",
    "    per_device_train_batch_size=1,\n",
    "    gradient_accumulation_steps=32,\n",
    "    per_device_eval_batch_size=32,\n",
    "    max_steps=10,\n",
    "    # num_train_epochs=1,\n",
    "    eval_strategy=\"steps\",\n",
    "    logging_steps=10,\n",
    "    save_total_limit=2,\n",
    "    learning_rate=5e-5,\n",
    "    weight_decay=0.01,\n",
    "    metric_for_best_model=\"f1\",\n",
    "    load_best_model_at_end=True,\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=trainset,\n",
    "    eval_dataset=testset,\n",
    "    compute_metrics=eval_function,\n",
    "    tokenizer=tokenizer,\n",
    "    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),\n",
    ")\n",
    "\n",
    "trainer_state = trainer.train()\n",
    "memory_info(start_gpu_memory, max_memory, trainer_state)"
   ],
   "id": "3850fd7416d78451",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "%%time\n",
    "start_gpu_memory, max_memory = init_memory()\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"./output\",\n",
    "    per_device_train_batch_size=1,\n",
    "    gradient_accumulation_steps=32,\n",
    "    gradient_checkpointing=True,\n",
    "    per_device_eval_batch_size=32,\n",
    "    max_steps=10,\n",
    "    # num_train_epochs=1,\n",
    "    eval_strategy=\"steps\",\n",
    "    logging_steps=10,\n",
    "    save_total_limit=2,\n",
    "    learning_rate=5e-5,\n",
    "    weight_decay=0.01,\n",
    "    metric_for_best_model=\"f1\",\n",
    "    load_best_model_at_end=True,\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=trainset,\n",
    "    eval_dataset=testset,\n",
    "    compute_metrics=eval_function,\n",
    "    tokenizer=tokenizer,\n",
    "    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),\n",
    ")\n",
    "\n",
    "trainer_state = trainer.train()\n",
    "memory_info(start_gpu_memory, max_memory, trainer_state)"
   ],
   "id": "a7105a885c50e459",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "%%time\n",
    "start_gpu_memory, max_memory = init_memory()\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"./output\",\n",
    "    per_device_train_batch_size=1,\n",
    "    gradient_accumulation_steps=32,\n",
    "    gradient_checkpointing=True,\n",
    "    per_device_eval_batch_size=32,\n",
    "    max_steps=10,\n",
    "    # num_train_epochs=1,\n",
    "    eval_strategy=\"steps\",\n",
    "    logging_steps=10,\n",
    "    save_total_limit=2,\n",
    "    learning_rate=5e-5,\n",
    "    weight_decay=0.01,\n",
    "    metric_for_best_model=\"f1\",\n",
    "    load_best_model_at_end=True,\n",
    "    optim=\"adafactor\",\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=trainset,\n",
    "    eval_dataset=testset,\n",
    "    compute_metrics=eval_function,\n",
    "    tokenizer=tokenizer,\n",
    "    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),\n",
    ")\n",
    "\n",
    "trainer_state = trainer.train()\n",
    "memory_info(start_gpu_memory, max_memory, trainer_state)"
   ],
   "id": "c9ff4522c4171e5c",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "%%time\n",
    "start_gpu_memory, max_memory = init_memory()\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"./output\",\n",
    "    per_device_train_batch_size=1,\n",
    "    gradient_accumulation_steps=32,\n",
    "    gradient_checkpointing=True,\n",
    "    per_device_eval_batch_size=32,\n",
    "    max_steps=10,\n",
    "    # num_train_epochs=1,\n",
    "    eval_strategy=\"steps\",\n",
    "    logging_steps=10,\n",
    "    save_total_limit=2,\n",
    "    learning_rate=5e-5,\n",
    "    weight_decay=0.01,\n",
    "    metric_for_best_model=\"f1\",\n",
    "    load_best_model_at_end=True,\n",
    "    optim=\"adafactor\",\n",
    ")\n",
    "\n",
    "for name, param in model.bert.named_parameters():\n",
    "    param.requires_grad = False\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=trainset,\n",
    "    eval_dataset=testset,\n",
    "    compute_metrics=eval_function,\n",
    "    processing_class=tokenizer,\n",
    "    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),\n",
    ")\n",
    "\n",
    "trainer_state = trainer.train()\n",
    "memory_info(start_gpu_memory, max_memory, trainer_state)"
   ],
   "id": "f24eec05dd04a9d8",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "67f24f9975fc1680",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
